using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

namespace test_device_sdk_csharp
{
    public partial class Form1 : Form
    {
        DataCallbackEventHandle _fpRequestEventHandler;
        DataCallbackFrameHandle _fpRequestFrameHandler;
        int m_hRealVideo;
        int m_hDecode;
        String m_strOutput;
        int m_hTalk;
        int m_hQuery;
        int m_hReplay;
        int m_hUpgrade;
        int m_hCapture;
        int m_hDownsnap;

        public Form1()
        {
            InitializeComponent();

            m_hRealVideo = 0;
            m_hDecode = 0;
            m_strOutput = "";
            m_hTalk = 0;
            m_hQuery = 0;
            m_hReplay = 0;
            m_hUpgrade = 0;
            m_hCapture = 0;
            m_hDownsnap = 0;

            timer1.Interval = 5000;
            timer1.Enabled = true;//表示启用timer控件
        }



        int RequestEventProc(Int64 llUserData, string strEvent, int event_type)
        {
            System.Console.WriteLine(strEvent);

            m_strOutput += "event type :";
            m_strOutput += event_type.ToString();
            m_strOutput += "   ";
            m_strOutput += strEvent;
            m_strOutput += "\r\n";

            return 0;
        }

        //视频帧回调
        int RequestFrameProc(IntPtr stream, IntPtr lpBuf, int size, Int64 llStamp, int type, int channel, Int64 llUserData)
        {
            //System.Console.WriteLine(strEvent);

            if (type == 0x70616e73)//em_FrameType_Snap_Frame
            {
                FileStream fsWrite = new FileStream("D:\tempcapture.jpg", FileMode.Append);
                byte[] ys = new byte[size];
                Marshal.Copy(lpBuf, ys, 0, size);
                fsWrite.Write(ys, 0, size);
                fsWrite.Close();
            }
            else if (type == 0x74616430)// em_FrameType_Data_Frame
            {
                FileStream fsWrite = new FileStream("D:\tempdown.jpg", FileMode.Append);
                byte[] ys = new byte[size];
                Marshal.Copy(lpBuf, ys, 0, size);
                fsWrite.Write(ys, 0, size);
                fsWrite.Close();
            }
            else if (type == 0x74736C66)//em_FrameType_FileList_Frame)
            {
                m_strOutput += "query file : ";
                m_strOutput += Marshal.PtrToStringAnsi(lpBuf); 
                m_strOutput += " \r\n";
            }
            else if (type == 0x6574736C)//em_FrameType_FileListEnd_Frame)
            {
                m_strOutput += "query file end: ";
                m_strOutput += Marshal.PtrToStringAnsi(lpBuf);
                m_strOutput += " \r\n";
            }
            else if (type == 0x74617473)//em_FrameType_FileListEnd_Frame)
            {
                m_strOutput += "upgrade end: ";
                m_strOutput += Marshal.PtrToStringAnsi(lpBuf);
                m_strOutput += " \r\n";
            }
            else if (type == 0x68643030)//em_FrameType_Header_Frame		= 0x68643030,	//realtime head frame('00dh')
            {   //实时视频流 头帧数据
                DecodeSdk.InputDecodeStream(m_hDecode, 1, lpBuf, size, llStamp);
            }
            else if (type == 0x69643030)//"00di" replay head frame
            {   //回放视频流 头帧数据
                DecodeSdk.InputDecodeStream(m_hDecode, 2, lpBuf, size, llStamp);
            }
            else if (type == 0x62643030 || type == 0x63643030 || type == 0x62773030)//iframe\  pframe \ audio frame
            {
                //视频流中 I帧（视频关键帧）、p帧（视频预测帧）、音频帧数据
                DecodeSdk.InputDecodeStream(m_hDecode, type, lpBuf, size, llStamp);
            }

            return 0;
        }

        private void button_start_Click(object sender, EventArgs e)
        {
            _fpRequestEventHandler = new DataCallbackEventHandle(this.RequestEventProc);
            _fpRequestFrameHandler = new DataCallbackFrameHandle(this.RequestFrameProc);

            st_work_param param;
            param.server = this.textBox_SvrIp.Text; //"192.168.1.100";
            param.port = int.Parse(textBoxServerPort.Text);

			param.callbackEvent = _fpRequestEventHandler;
            param.callbackFrame = _fpRequestFrameHandler;//视频帧数据回调接口
            param.llUserData = 0;

            DeviceSdk.SDS_NetDevice_Init(param);//sdk 启动监听
            DecodeSdk.dec_Init();
        }

        private void button_stop_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_Uninit();
            DecodeSdk.dec_Uninit();
        }

        private void button_getgps_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_GetGPS("", 1);
        }

        private void button_getalarm_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_GetAlarm("", 1);
        }

        private void button_stopgps_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_GetGPS("", 0);
        }

        private void button_stopalarm_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_GetAlarm("", 0);
        }

        private void button_getinfo_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_RequestDeviceInfo(textBox_deviceid.Text);
        }

        private void button_openstream_Click(object sender, EventArgs e)
        {
            //open video
            DeviceSdk.SDS_NetDevice_OpenStream(textBox_deviceid.Text, int.Parse(textBox_channel.Text), 0, ref m_hRealVideo);


            m_hDecode = DecodeSdk.OpenDecodeChan(pictureBox1.Handle, 0);
            DecodeSdk.CtrlPlay(m_hDecode, 3, 1);
        }

        private void button_closestream_Click(object sender, EventArgs e)
        {
            if (m_hRealVideo != 0)
            {
                DeviceSdk.SDS_NetDevice_CloseStream(m_hRealVideo);
                m_hRealVideo = 0;

                DecodeSdk.CloseDecodeChan(m_hDecode);
                m_hDecode = 0;
            }

        }

        private void button_ptz_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_PtzCtrlOnStream(m_hRealVideo, (int)ePtzActionType.ePtzActionUp, 10, 10);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            richTextBox_output.Text = m_strOutput;

            if (richTextBox_output.Text.Length > 20000)
                richTextBox_output.Text = "";

            if (m_hTalk != 0)
            {
                byte[] audio_data = new byte[104];
                audio_data[1] = 1;
                audio_data[2] = 0x32;
                IntPtr ptr = Marshal.AllocHGlobal(audio_data.Length);
                for(int i = 0; i < 10; i++)
                    DeviceSdk.SDS_NetDevice_TalkSend(m_hTalk, 0, ptr, 104);
            }
        }

        private void button_opentalk_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_TalkStart(textBox_deviceid.Text, 0, ref m_hTalk);

            m_hDecode = DecodeSdk.OpenDecodeChan(pictureBox1.Handle, 0);
            DecodeSdk.CtrlPlay(m_hDecode, 3, 1);
        }

        private void button_closetalk_Click(object sender, EventArgs e)
        {
            if (m_hTalk != 0)
            {
                DeviceSdk.SDS_NetDevice_TalkStop(m_hTalk);
                m_hTalk = 0;

                DecodeSdk.CloseDecodeChan(m_hDecode);
                m_hDecode = 0;
            }
        }

        private void button_openquery_Click(object sender, EventArgs e)
        {
            if (m_hQuery != 0)
            {
                DeviceSdk.SDS_NetDevice_CloseQuery(m_hQuery);
                m_hQuery = 0;
            }

            DeviceSdk.SDS_NetDevice_Query(textBox_deviceid.Text, 3, "180207 000000", "235959", 98, ref m_hQuery);
        }

        private void button_closequery_Click(object sender, EventArgs e)
        {
            if(m_hQuery != 0)
            {
                DeviceSdk.SDS_NetDevice_CloseQuery(m_hQuery);
                m_hQuery = 0;
            }

        }

        private void button_openreplay_Click(object sender, EventArgs e)
        {
			//	if endPos is set to 0, SDK will replay the whole video file.
            DeviceSdk.SDS_NetDevice_ReplayStart(textBox_deviceid.Text, 1, "/var/disk0/rec_file/rec0166.cv1", 
				0, 0, 0, ref m_hReplay);

            m_hDecode = DecodeSdk.OpenDecodeChan(pictureBox1.Handle, 0);
            DecodeSdk.CtrlPlay(m_hDecode, 3, 1);
        }

        private void button_closereplay_Click(object sender, EventArgs e)
        {
            if(m_hReplay != 0)
            {
                DeviceSdk.SDS_NetDevice_ReplayStop(m_hReplay);
                m_hReplay = 0;

                DecodeSdk.CloseDecodeChan(m_hDecode);
                m_hDecode = 0;
            }

        }

        private void button_upgrade_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_UpgradeStart(textBox_deviceid.Text, "H:\\M21xx-APP-VH26501.crc", "M21xx-APP-VH26501.crc", ref m_hUpgrade); //V1703291
        }

        private void button_closeupgrade_Click(object sender, EventArgs e)
        {
            if(m_hUpgrade != 0)
            {
                DeviceSdk.SDS_NetDevice_UpgradeStop(m_hUpgrade);
                m_hUpgrade = 0;
            }
        }

        private void button_getiostatus_Click(object sender, EventArgs e)
        {
            int dwInputStatus = 0;
            int nInputCount = 0;
            int dwOutputStatus = 0;
            int nOutputCount = 0;
            DeviceSdk.SDS_NetDevice_GetIoStatus(textBox_deviceid.Text, ref dwInputStatus, ref nInputCount, ref dwOutputStatus, ref nOutputCount);
        }

        private void button_iocontrol_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_Ctrl(textBox_deviceid.Text, (int)eCtrlType.eOil_cutoff);
        }

        private void button_opensnap_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_Capture(textBox_deviceid.Text, 1, ref m_hCapture);
        }

        private void button_closesnap_Click(object sender, EventArgs e)
        {
            if (m_hCapture != 0)
            {
                DeviceSdk.SDS_NetDevice_CloseCapture(m_hCapture);
                m_hCapture = 0;
            }
        }

        private void button_downsnap_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_DownloadSnap(textBox_deviceid.Text, "/var/disk1/pic/2017-12-19/10002_175431_1.jpg", ref m_hDownsnap);
        }

        private void button_closedownsnap_Click(object sender, EventArgs e)
        {
            if(m_hDownsnap != 0)
            {
                DeviceSdk.SDS_NetDevice_CloseDownloadSnap(m_hDownsnap);
                m_hDownsnap = 0;
            }
        }

        private void button_tranmessage_Click(object sender, EventArgs e)
        {
            st_device_config inConfig = new st_device_config();
            inConfig.Buffer = "<VariCfgSec Action = \"DEVICE_QUERY\"><stVersion/></VariCfgSec>";
            inConfig.Length = inConfig.Buffer.Length;
            
            DeviceSdk.SDS_NetDevice_TranConfigEx(textBox_deviceid.Text, 0, ref inConfig);
        }

        private void button_search_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_Search((int)6688);
        }

        private void button_stopsearch_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_StopSearch();
        }

        private void button_directopenvideo_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_DirectOpenStream(textBox_deviceip.Text, 6688, int.Parse(textBox_channel.Text), 0, ref m_hRealVideo);

            m_hDecode = DecodeSdk.OpenDecodeChan(pictureBox1.Handle, 0);
            DecodeSdk.CtrlPlay(m_hDecode, 3, 1);
        }

        private void button_directclosevideo_Click(object sender, EventArgs e)
        {
            if (m_hRealVideo != 0)
            {
                DeviceSdk.SDS_NetDevice_DirectStopStream(m_hRealVideo);
                m_hRealVideo = 0;

                DecodeSdk.CloseDecodeChan(m_hDecode);
                m_hDecode = 0;
            }
        }

        private void button_directptz_Click(object sender, EventArgs e)
        {
            DeviceSdk.SDS_NetDevice_DirectPtzCtrl(textBox_deviceip.Text, 6688, int.Parse(textBox_channel.Text), (int)ePtzActionType.ePtzActionUp, 10, 10);
        }
    }
}
